<?php

namespace app\admin\controller;

use app\common\service\Permission as PermissionService;
use app\common\validate\Permission as PermissionValidate;
use think\Controller;
use think\Request;

class Permission extends Controller
{

    /**
     * 显示资源列表
     * @param Request $request
     */
    public function index(Request $request)
    {
        $page = $request->get('page',1);
        $pageSize = $request->get('page_size',10);
        $keywords = $request->get("keywords","");
        $service = new PermissionService();
        $data = $service->getList($page,$pageSize,$keywords);
        $this->success('获取成功','',$data);
    }

    /**
     * 获取权限树
     */
    public function tree(){
        $service = new PermissionService();
        $data = $service->tree();
        $this->success("获取成功",'',$data);
    }

    /**
     * 保存新建的资源
     * @param Request $request
     */
    public function save(Request $request)
    {
        $data = $request->post();
        $validate = new PermissionValidate();
        if(!$validate->scene("save")->check($data)){
            $this->error($validate->getError());
        }
        $service = new PermissionService();
        try{
            $id = $service->save($data);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success("操作成功");
    }


    /**
     * 显示指定的资源
     * @param $id
     */
    public function read($id)
    {
        $service = new PermissionService();
        $data = $service->read($id);
        $this->success("操作成功","",$data);
    }


    /**
     *
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    /**
     * 保存更新的资源
     * @param Request $request
     * @param $id
     */
    public function update(Request $request, $id)
    {
        $data = $request->post();
        $validate = new PermissionValidate();
        if(!$validate->scene("update")->check($data)){
            $this->error($validate->getError());
        }
        $service = new PermissionService();
        $res = $service->update($data,$id);
        if($res){
            $this->success("操作成功");
        }
        $this->error("操作失败");
    }


    /**
     * 删除指定资源
     * @param $id
     */
    public function delete($id)
    {
        $service = new PermissionService();
        $res = $service->delete($id);
        if($res){
            $this->success("操作成功","");
        }
        $this->error("操作失败","");
    }
}
